package com.zhixun.zhlq.controller;

import com.zhixun.zhlq.entity.SysUserEntity;
import com.zhixun.zhlq.service.SysLogsService;
import com.zhixun.zhlq.utils.BsResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@Api(value = "LoginController", tags = "登录", description = "登录登出相关接口", position = 1)
@RestController
@RequestMapping("/pc")
@Slf4j
public class LoginController {

    @Autowired
    private SysLogsService sysLogsService;


    /**
     * 登录认证
     */
    @ApiOperation(value = "PC登录", notes = "PC登录")
    @GetMapping(value = "/login")
    public BsResult login(HttpServletRequest request, @RequestParam String username, @RequestParam String password) {
        try {
            SysUserEntity principal = checkToken(request, username, password);
            BsResult bsResult = BsResult.ok();
            bsResult.put("data", principal);
            return bsResult;
        } catch (NullPointerException | AuthenticationException e) {
            return BsResult.error(e.getMessage());
        } catch (Exception e) {
            return BsResult.error500();
        }
    }

    public SysUserEntity checkToken(HttpServletRequest request, String username, String password) {
        if ("".equals(username.trim())) {
            throw new NullPointerException("账号不能为空！");
        }
        if ("".equals(password.trim())) {
            throw new NullPointerException("密码不能为空！");
        }
        // 根据用户名和密码创建 Token
        UsernamePasswordToken token = new UsernamePasswordToken(username,password,true,null);
        //UsernamePasswordToken token = new UsernamePasswordToken(username);
        // 获取 subject 认证主体
        Subject subject = SecurityUtils.getSubject();
        try{
            // 开始认证，这一步会跳到我们自定义的 Realm 中
            subject.login(token);
            SysUserEntity principal = (SysUserEntity) subject.getPrincipal();
            //添加登录日志
            sysLogsService.add(request, "login", "登录了系统！", principal.getId(), principal.getNickName());
            principal.setPassword(null);
            return principal;
        }catch(AuthenticationException e){
            throw new AuthenticationException("用户名或密码错误！");
        }
    }
}
